package core

import (
	"embed"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"

	"gitee.com/StarCitizen_CN/logger"
)

func CheckAndCrateOsTemp() error {
	_, err := os.Stat(TempDir)
	if errors.Is(err, fs.ErrNotExist) {
		err = os.Mkdir(TempDir, os.ModeDir)
	}
	if err != nil {
		return err
	}

	return nil
}

func WriteEmbedEntrysTo(embedDir *embed.FS, f fs.DirEntry, rootPath string, parentNode string) error {

	currentNode := fmt.Sprintf("%s/%s", parentNode, f.Name())
	currentPath := filepath.Join(rootPath, strings.ReplaceAll(currentNode, "/", "\\"))

	logger.Debug("测试 %s %s %s\n", f.Name(), currentPath, currentNode)

	if f.IsDir() {
		_, err := os.Stat(currentPath)
		if os.IsNotExist(err) {
			err = nil
			err = os.MkdirAll(currentPath, os.ModePerm)
			logger.Debug("创建目录 %s", currentPath)
		}
		if err != nil {
			return err
		}

		fileEntitys, _ := embedDir.ReadDir(currentNode)
		for _, entity := range fileEntitys {
			err = WriteEmbedEntrysTo(embedDir, entity, rootPath, currentNode)
			if err != nil {
				return err
			}
		}
	} else {

		_ = os.Remove(currentPath)

		parrentPath := filepath.Dir(currentPath)
		os.MkdirAll(parrentPath, os.ModePerm)
		logger.Debug("创建 %s", parrentPath)

		data, readErr := embedDir.ReadFile(currentNode)
		if readErr != nil {
			logger.Err(readErr)
			return readErr
		}
		logger.Debug("read size %d", len(data))
		err := os.WriteFile(currentPath, data, os.ModeAppend)
		if err != nil {
			logger.Err(err)
			return err
		}

	}
	return nil
}
